package xyz.xtt.asset.mq;

import java.nio.charset.StandardCharsets;
import java.util.Objects;

import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import xyz.xtt.asset.vo.GmtEventMsgRequestVo;
import xyz.xtt.asset.vo.GmtResponseVo;

@RefreshScope
@Slf4j
@Component
@RocketMQMessageListener(topic = "nft-asset-event-msg", selectorExpression = "${nft_asset_event_msg_callback_group.selectorExpression}", consumerGroup = "${rocketmq.consumer.group.nft_asset_event_msg_callback_group}")
public class EventMsgCallBack implements RocketMQListener<MessageExt> {
	@Value("${asset.event.msg.callbackUrl}")
	private String callBackUrl;

	@Override
	public void onMessage(MessageExt msg) {
		String msgId = msg.getMsgId();
		log.info("msgId:{}", msgId);
		byte[] body = msg.getBody();
		String message = new String(body, StandardCharsets.UTF_8);
		boolean callback = callback(message, callBackUrl);
		if (callback) {
			log.info("msgId:{} url:{} callback ok", msgId, callBackUrl);
		}
	}

	public static boolean callback(String message, String url) {
		GmtEventMsgRequestVo build = GmtEventMsgRequestVo.buildEvengMsg(message);
		String jsonStr = JSONUtil.toJsonStr(build);
		HttpResponse response = HttpRequest
				.post(url)
				.contentType("text/plain") // 使用contentType方法设置Content-Type
				.body(jsonStr)
				.execute();
		String responseBody = response.body();
		Boolean result = Boolean.FALSE;
		if (Objects.equals(true, response.isOk())) {
			GmtResponseVo gmtResponse = JSONUtil.toBean(responseBody, GmtResponseVo.class);
			result = response.isOk() && Objects.nonNull(response) && gmtResponse.isOk();
			if (Objects.equals(Boolean.FALSE, result)) {
				log.info("responseBody:{},callback result:{}", JSONUtil.toJsonStr(gmtResponse), result);
			}
		}
		if (Objects.equals(Boolean.FALSE, result)) {
			log.info("jsonStr:{},url:{},responseBody{}", jsonStr, url, responseBody);
			throw new RuntimeException("onMessage EventMsgCallBack");
		}
		return true;
	}

}
